<?php

namespace app\admin\service;

use app\admin\model\BoxGametaskConfig;
use app\qsapi\model\BoxTaskExchangeCdk;
use think\Exception;

class BoxGametaskConfigService extends BaseService
{
    /**
     * 构造函数
     * LevelService constructor.
     */
    public function __construct()
    {
        $this->model = new BoxGametaskConfig();
    }

    public function getList()
    {
        $param  = request()->param();
        $status = $param['status'] ?? '';
        $map    = [];

        if (!empty($param['time_range'][0]) && !empty($param['time_range'][1])) {
            $map[] = ['a.create_time', '>=', $param['time_range'][0]];
            $map[] = ['a.create_time', '<=', $param['time_range'][1]];
        }

        if (!empty($param['game_name'])) {
            $map[] = ['c.game_name', '=', $param['game_name']];
        }

        /**
         * 1.待上架, 到时间点然后没有上架的游戏
         * 2.已上架
         * 3.已下架
         * 4.上架即将开始, 上架了但是没有到时间点,此时有倒计时
         * 5.上架进行中, 在时间点之内, 但是没有结束的游戏
         * 6.上架已结束, 到时间点之后, 并且已经结束的游戏
         */
        $today = date('Y-m-d H:i:s');
        switch ($status) {
            case 1:
                $map[] = ['a.status', '=', 2];
                $map[] = ['a.start_time', '<=', $today];
                $map[] = ['a.end_time', '>=', $today];
                break;
            case 2:
                $map[] = ['a.status', '=', 1];
                break;
            case 3:
                $map[] = ['a.status', '=', 2];
                break;
            case 4:
                $map[] = ['a.status', '=', 1];
                $map[] = ['a.start_time', '>', $today];
                break;
            case 5:
                $map[] = ['a.status', '=', 1];
                $map[] = ['a.start_time', '<=', $today];
                $map[] = ['a.end_time', '>=', $today];
                break;
            case 6:
                $map[] = ['a.status', '=', 1];
                $map[] = ['a.end_time', '<', $today];
                break;
            default:
        }


        $boxArticleList = $this->model->alias('a')
            ->field('a.*,c.game_name,d.name as server_name')
//            ->field('a.*,c.game_name')
            ->leftJoin('cq_box_game c', 'a.game_id = c.id')
            ->leftJoin('cq_box_game_open d', 'a.server_id = d.server_id and a.game_id = d.game_id and d.mark = 1')
            ->where($map)
            ->group('a.id')
            ->order('a.id desc');

        $list = $boxArticleList->paginate($param['limit']);
        if (empty($list)) {
            return message('暂无数据!', false);
        }
        $list = $list->toArray();
//        foreach ($list['data'] as &$value) {
//            $openData = (new BoxGameOpen())->field('name')
//                ->where(['server_id' => $value['server_id'], 'game_id' => $value['game_id'], 'mark' => 1])
//                ->find();
//            $value['server_name'] = $openData['name'];
//        }

        //返回结果
        return array (
            "msg"   => '操作成功',
            "code"  => 0,
            "data"  => $list['data'],
            "count" => $list['total'],
        );
    }


    //添加/修改
    public function edit()
    {
        $param                = request()->param();
        $param['start_time']  = $param['time_range'][0] ?? '';
        $param['end_time']    = $param['time_range'][1] ?? '';
        $param['task_award']  = isset($param['task_award']) ? json_encode($param['task_award']) : '';
        $param['create_time'] = date('Y-m-d H:i:s');
        if (!is_numeric($param['game_id']) || empty($param['game_id'])) {
            return message('游戏ID为空,请选择游戏后再操作!', false);
        }
        if (!is_numeric($param['server_id']) || empty($param['server_id'])) {
            return message('区服ID为空,请前往(开服配置)区服ID后操作!', false);
        }
        return parent::edit($param); // TODO: Change the autogenerated stub
    }

    //修改状态
    public function status()
    {
        return parent::status(); // TODO: Change the autogenerated stub
    }

    //获取CDK列表
    public function getCdkList(): array
    {
        $param = request()->param();

        // 查询条件
        $map = [];
        // 游戏
        if (!empty($param['task_id'])) {
            $map[] = ['gametask_id', '=', $param['task_id']];
        }
        $map[] = ['mark','=', 1];

        $list            = (new BoxTaskExchangeCdk())
            ->where($map)
            ->order('id', 'desc')
            ->page(PAGE, PERPAGE)
            ->select();
        $count           = (new BoxTaskExchangeCdk())->where($map)->count();
        $result          = message("操作成功", true, $list);
        $result['count'] = $count;
        return $result;
    }

    /**
     * @Notes:导入接口
     * @Date: 2023/12/11
     * @Time: 10:05
     * @Interface import
     */
    public function import()
    {
        $param  = request()->param();
        $taskId = $param['task_id'];
        // 上传文件(非图片)
        $result = upload_file('exchange_file', '', $error);
        if (!$result) {
            return $this->jsonReturn(message($error, false));
        }

        // 文件路径
        if (is_array($result)) {
            $result = $result['file_name'];
        }
        $filePath = UPLOAD_TEMP_PATH . '/' . $result;
        if (!file_exists($filePath)) {
            return $this->jsonReturn(message("文件不存在", false));
        }
        // 读取文件
        $objPHPExcel   = \PHPExcel_IOFactory::load($filePath); //获取sheet表格数目
        $sheetCount    = $objPHPExcel->getSheetCount(); //默认选中sheet0表
        $sheetSelected = 0;
        $objPHPExcel->setActiveSheetIndex($sheetSelected); //获取表格行数
        $rowCount    = $objPHPExcel->getActiveSheet()->getHighestRow(); //获取表格列数
        $columnCount = $objPHPExcel->getActiveSheet()->getHighestColumn();
        // 计数器
        $i    = 0;
        $data = array ();
        // 循环读取行数据
        for ($row = 2; $row <= $rowCount; $row++) {
            // 名称
            $data[$i]['gametask_id'] = $taskId;
            $cdkData                 = $objPHPExcel->getActiveSheet()->getCell("A" . $row)->getValue();
            if (empty($cdkData)) {
                continue;
            }
            $data[$i]['cdk'] = $objPHPExcel->getActiveSheet()->getCell("A" . $row)->getValue();
            $i++;
//            // 插入数据
//            $exchangeCdk              = new ActivityExchangeCdk();
//            $exchangeCdk->exchange_id = $exchangeId;
//            $exchangeCdk->cdk         = $cdk;
//            if ($exchangeCdk->save()) {
//                $i++;
//            }
        }
        // 插入数据
        $result = BoxTaskExchangeCdk::insertAll($data);

        $model            = (new BoxGametaskConfig())->where('id', $param['task_id'])->find();
        $model->num       += $result;
        $model->total_num += $result;
        $model->save();

        return message("本次共导入{$result}条数据", true);
    }

    public function delete()
    {
        try {
            $params = request()->param();
            $taskId = $params['task_id'] ?? 0;
            if (empty($taskId)) {
                return message("任务ID不能为空", false, $params);
            };

            if($params['is_all'] === 1){
                $map[] = ['gametask_id', '=', $taskId];
                $map[] = ['is_get', '=', 0];
                (new BoxTaskExchangeCdk())->where($map)->delete();
                return message("删除所有未领取CDK成功!(注意:已领取的CDK无法删除)", true);
            }

            $ids = $params['id'] ?? [];
            if (is_array($ids) && !empty($ids)) {
                (new BoxTaskExchangeCdk())->where('is_get', 'neq', 1)->where('gametask_id', $taskId)->whereIn('id', $ids)->delete();
                return message("删除成功!(注意:已领取的CDK无法删除)", true);
            }

        } catch (Exception $e) {
            return message($e->getMessage(), false);
        }

    }

}